package com.example.quanxin.service;/*
 *
 *   welcome:11311
 *   创建时间:2023/5/20
 *
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.quanxin.config.GlobalConfig;
import com.example.quanxin.entity.*;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiStudentService {

    @Resource
    private ApiService apiService;

    public static Boolean getAndStoreCookies(LoginParam loginParam) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    Map<String, List<Cookie>> globalCookieMap = GlobalConfig.getGlobalCookieMap();
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        globalCookieMap.put("mouxiangyang", cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = globalCookieMap.get("mouxiangyang");
                        return cookies != null ? cookies : new ArrayList<>();
                    }
                })
                .build();

        RequestBody formBody = new FormBody.Builder()
                .add("fid", "-1")
                .add("uname", (loginParam != null && loginParam.getUsername() != null) ? loginParam.getUsername() : "c415p589IchOgWQMg2oBzQ==")
                .add("password", (loginParam != null && loginParam.getPassword() != null) ? loginParam.getPassword(): "5FP7JSi9CSy+nCwQ5Dhc6A==")
                .add("refer", "https://i.chaoxing.com")
                .add("t", "true")
                .add("forbidotherlogin", "0")
                .add("validate", "")
                .add("doubleFactorLogin", "0")
                .add("independentId", "0")
                .build();

        Request request = new Request.Builder()
                .url("https://passport2.chaoxing.com/fanyalogin")
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            log.info("response{}",response);
        }catch (Exception e){
            throw new RuntimeException("获取token失败");
        }


        return true;
    }
    static OkHttpClient client = new OkHttpClient.Builder()
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                    try {
//                        getAndStoreCookies(new LoginParam());
//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }
//                    globalCookieMap.put("quanxin", cookies);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = GlobalConfig.getCookies("mouxiangyang");
                    return cookies != null ? cookies : new ArrayList<>();
                }
            })
            .build();

    public OkHttpClient anotherClient = new OkHttpClient.Builder().build();


    /**
     * 获取课程成绩
     * */
    public ClassScoreAvg getClassScore(Long courseId,Long classId,Long cpi,Long personId,ClassScoreAvg result) throws Exception {
         Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/work-stastics/stu-works?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc=&page=1&pageSize=16&personId="+personId)
                .get()
                .build();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            log.info("response:{}",string);
            JSONObject jsonObject = JSON.parseObject(string);
            Map<String, Double>  map=new HashMap<>();
             JSONArray jsonArray = jsonObject.getJSONArray("data");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                Double avgWorkScore1 = tmp.getDouble("stuOriginScore");
                String title= tmp.getString("title");
                map.put(title,avgWorkScore1);
            }
            List<Double> stuOriginScore = new ArrayList<>();
            for (String name:
            result.getWorkPostCountArr()) {
                Double v = map.get(name);
                stuOriginScore.add(v);
            }
//            result.setWorkPostCountArr(GlobalConfig.getWorkPostCountArr());
            result.setStuOriginScore(stuOriginScore);
        }catch (Exception e){
            log.info("错误为{}",e);
            //            throw new Exception("获取分数失败");
            return result;
        }
        return result;
    }



    /**
     * 获取课程进度
     * */
    public List<StudentChapter>  getClassSchedule(Long courseId,Long classId,Long cpi,String pEnc,String uname,String password,Long courseCpi) throws Exception {
        Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/task/s/progress/detail?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc="+pEnc+"&page=1&pageSize=16&status=0")
                .get()
                .build();
        List<StudentChapter> studentChapterList = new ArrayList<>();
        Map<String, Double> classSchedule = apiService.getClassSchedule(courseId, classId, courseCpi);
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            log.info("response:{}",string);
            JSONObject jsonObject = JSON.parseObject(string);
            Map<String, Double>  map=new HashMap<>();
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("results");
            Integer tasksNumber=0;//每个章节任务数量
            Integer chapter=1;//章节数
            Integer tasksStudentNumber=0;//每个章节学生任务完成量
            String tmpName = jsonArray.getJSONObject(0).getString("name");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                String label = tmp.getString("label").substring(0, 1);
                if  (label.equals(chapter.toString())){
                       tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                       tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                }else{
                    StudentChapter studentChapter =new StudentChapter();
                    studentChapter.setName(tmpName);
                    studentChapter.setTasksStudentNumber(tasksStudentNumber);
                    studentChapter.setTasksNumber(tasksNumber);
                    studentChapter.setTasksPass(tasksNumber*0.6);
                    Double v = classSchedule.get(tmpName);
                    studentChapter.setTasksAvg(v);
                    studentChapterList.add(studentChapter);
                            tasksNumber=0;//重置每个章节任务数量
//                            chapter=chapter+1;//章节数+1
                            tasksStudentNumber=0;//重置每个章节学生任务完成量
                    chapter=chapter+1;//章节数+1
                    tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                    tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                    tmpName = tmp.getString("name");
                }
            }
            JSONObject pageInfo =  jsonObject.getJSONObject("data").getJSONObject("pageInfo");
            for (int i=2;i<=pageInfo.getInteger("totalPage");i++){
//                LoginParam loginParam = new LoginParam();
//                loginParam.setUsername(uname);
//                loginParam.setUsername(password);
//                this.getAndStoreCookies(loginParam);
                Request  request1 = new Request.Builder()
                        .url("https://stat2-ans.chaoxing.com/stat2/task/s/progress/detail?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc="+pEnc+"&page="+i+"&pageSize=16&status=0")
                        .get()
                        .build();
                try(Response Response1 = client.newCall(request1).execute()) {
                    string = Response1.body().string();
//                    workPostCountArr = GlobalConfig.getWorkPostCountArr();
                    log.info("response:{}",string);
                    jsonObject = JSON.parseObject(string);
                    jsonArray = jsonObject.getJSONObject("data").getJSONArray("results");

                    for(int j = 0; j < jsonArray.size(); j ++){
                        JSONObject tmp = jsonArray.getJSONObject(j);
                        String label = tmp.getString("label").substring(0, 1);
                        if  (label.equals(chapter.toString())){
                            tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                            tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                        }else{
                            StudentChapter studentChapter =new StudentChapter();
                            studentChapter.setName(tmpName);
                            studentChapter.setTasksStudentNumber(tasksStudentNumber);
                            studentChapter.setTasksNumber(tasksNumber);
                            studentChapter.setTasksPass(tasksNumber*0.6);
                            Double v = classSchedule.get(tmpName);
                            studentChapter.setTasksAvg(v);
                            studentChapterList.add(studentChapter);
                            tasksNumber=0;//重置每个章节任务数量
//                            chapter=chapter+1;//章节数+1
                            tasksStudentNumber=0;//重置每个章节学生任务完成量
                            chapter=chapter+1;//章节数+1
                            tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                            tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                            tmpName = tmp.getString("name");

                        }
                    }
                }catch (Exception e){
                    log.info("错误为{}",e);
//            throw new Exception("获取分数失败");
                    return null;
                }
            }
            StudentChapter studentChapter =new StudentChapter();
            studentChapter.setName(tmpName);
            studentChapter.setTasksStudentNumber(tasksStudentNumber);
            studentChapter.setTasksNumber(tasksNumber);
            studentChapter.setTasksPass(tasksNumber*0.6);
            Double v = classSchedule.get(tmpName);
            studentChapter.setTasksAvg(v);
            studentChapterList.add(studentChapter);
        }catch (Exception e){
            log.info("错误为{}",e);
//            throw new Exception("获取分数失败");
            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            for (String i:workPostCountArr) {
                StudentChapter studentChapter =new StudentChapter();
                studentChapter.setName(i);
                studentChapter.setTasksStudentNumber(0);
                studentChapter.setTasksNumber(0);
                studentChapter.setTasksPass(0.0);
                Double v = classSchedule.get(0.0);
                studentChapter.setTasksAvg(v);
                studentChapterList.add(studentChapter);
            }
            return studentChapterList;
        }
        return studentChapterList;
    }


    /**
     * 获取课程完成情况
     * */
    public ClassJob getClassJob(Long courseId,Long classId,Long cpi,String pEnc,Long courseCpi) throws Exception {
        Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/study-data/job?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc="+pEnc)
                .get()
                .build();
        ClassJob classJob=new ClassJob();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            log.info("response:{}",string);
            JSONObject jsonObject = JSON.parseObject(string);
            Map<String, Double>  map=new HashMap<>();
            JSONObject jsonArray = jsonObject.getJSONObject("data");
            Integer job = jsonArray.getInteger("job");
            Integer publishJobNum=jsonArray.getInteger("publishJobNum");
            classJob.setJob(job);
            classJob.setPublishJobNum(publishJobNum);
            classJob.setPublishJobIncomplete(publishJobNum-job);
            classJob.setJobProportion((job*1.0)/publishJobNum);
            Map<String, Double> classSchedule = apiService.getClassSchedule(courseId, classId, courseCpi);
            double totalValue = 0.0; // 初始化总值为0.0
            for (Double value : classSchedule.values()) { // 获取所有value的集合
                totalValue += value; // 将当前value添加到总和中
            }
            classJob.setAvgJob(totalValue);
            Double avgJobProportion=totalValue/publishJobNum;
            classJob.setAvgJobProportion(avgJobProportion);
            classJob.setExceedJobProportion(((job*1.0)/publishJobNum)-avgJobProportion);
        }catch (Exception e){
            log.info("错误为{}",e);
            //            throw new Exception("获取分数失败");
            classJob.setJob(0);
            classJob.setPublishJobNum(0);
            classJob.setPublishJobIncomplete(0);
            classJob.setJobProportion(0.0);
            classJob.setAvgJob(0.0);
            classJob.setAvgJobProportion(0.0);
            classJob.setExceedJobProportion(0.0);
            return classJob;
        }
        return classJob;
    }


    /**
     * 获取课程进度
     * */
    public List<StudentClassSchedule>  getStudentClassSchedule(Long courseId,Long classId,Long cpi,String pEnc) throws Exception {
        Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/task/s/progress/detail?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc="+pEnc+"&page=1&pageSize=16&status=0")
                .get()
                .build();
        List<StudentClassSchedule> studentChapterList = new ArrayList<>();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            log.info("response:{}",string);
            JSONObject jsonObject = JSON.parseObject(string);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("results");
            Integer tasksNumber=0;//每个章节任务数量
            Integer chapter=1;//章节数
            Integer tasksStudentNumber=0;//每个章节学生任务完成量
            String tmpName = jsonArray.getJSONObject(0).getString("name");

            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                String label = tmp.getString("label").substring(0, 1);
                if  (label.equals(chapter.toString())){
                    tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                    tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                }else{
                    StudentClassSchedule studentChapter =new StudentClassSchedule();
                    studentChapter.setName(tmpName);
                    studentChapter.setTasksStudentNumber(tasksStudentNumber);
                    studentChapter.setTasksNumber(tasksNumber);
                    double v = tasksStudentNumber * 1.0 / tasksNumber;
                    studentChapter.setTasksStudentProportion(v);
                    if (v<0.6){
                        studentChapter.setType(1);
                    }else if (v<0.8){
                        studentChapter.setType(2);
                    }else{
                        studentChapter.setType(3);
                    }
                    studentChapterList.add(studentChapter);
                    tasksNumber=0;//重置每个章节任务数量
//                            chapter=chapter+1;//章节数+1
                    tasksStudentNumber=0;//重置每个章节学生任务完成量
                    chapter=chapter+1;//章节数+1
                    tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                    tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                    tmpName = tmp.getString("name");
                }
            }
            JSONObject pageInfo =  jsonObject.getJSONObject("data").getJSONObject("pageInfo");
            for (int i=2;i<=pageInfo.getInteger("totalPage");i++){
                Request  request1 = new Request.Builder()
                        .url("https://stat2-ans.chaoxing.com/stat2/task/s/progress/detail?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc="+pEnc+"&page="+i+"&pageSize=16&status=0")
                        .get()
                        .build();
                try(Response Response1 = client.newCall(request1).execute()) {
                    string = Response1.body().string();
                    log.info("response:{}",string);
                    jsonObject = JSON.parseObject(string);
                    jsonArray = jsonObject.getJSONObject("data").getJSONArray("results");

                    for(int j = 0; j < jsonArray.size(); j ++){
                        JSONObject tmp = jsonArray.getJSONObject(j);
                        String label = tmp.getString("label").substring(0, 1);
                        if  (label.equals(chapter.toString())){
                            tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                            tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                        }else{
                            StudentClassSchedule studentChapter =new StudentClassSchedule();
                            studentChapter.setName(tmpName);
                            studentChapter.setTasksStudentNumber(tasksStudentNumber);
                            studentChapter.setTasksNumber(tasksNumber);
                            double v = tasksStudentNumber * 1.0 / tasksNumber;
                            studentChapter.setTasksStudentProportion(v);
                            if (v<0.6){
                                studentChapter.setType(1);
                            }else if (v<0.8){
                                studentChapter.setType(2);
                            }else{
                                studentChapter.setType(3);
                            }
                            studentChapterList.add(studentChapter);
                            tasksNumber=0;//重置每个章节任务数量
//                            chapter=chapter+1;//章节数+1
                            tasksStudentNumber=0;//重置每个章节学生任务完成量
                            chapter=chapter+1;//章节数+1
                            tasksStudentNumber=tasksStudentNumber+tmp.getInteger("completeNum");
                            tasksNumber=tasksNumber+tmp.getJSONArray("list").size();
                            tmpName = tmp.getString("name");

                        }
                    }
                }catch (Exception e){
                    log.info("错误为{}",e);
//            throw new Exception("获取分数失败");
                    return null;
                }
            }
            StudentClassSchedule studentChapter =new StudentClassSchedule();
            studentChapter.setName(tmpName);
            studentChapter.setTasksStudentNumber(tasksStudentNumber);
            studentChapter.setTasksNumber(tasksNumber);
            double v = tasksStudentNumber * 1.0 / tasksNumber;
            studentChapter.setTasksStudentProportion(v);
            if (v<0.6){
                studentChapter.setType(1);
            }else if (v<0.8){
                studentChapter.setType(2);
            }else{
                studentChapter.setType(3);
            }
            studentChapterList.add(studentChapter);
        }catch (Exception e){
            log.info("错误为{}",e);
            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            for (String i:workPostCountArr) {
                StudentClassSchedule studentChapter =new StudentClassSchedule();
                studentChapter.setName(i);
                studentChapter.setTasksStudentNumber(0);
                studentChapter.setTasksNumber(0);
                studentChapter.setTasksStudentProportion(0.0);
                studentChapter.setType(1);
                studentChapterList.add(studentChapter);
            }
            return studentChapterList;
        }
        return studentChapterList;
    }



    /**
     * 课程任务完成情况汇总
     * */
    public ClassScoreSummary getClassScoreSummary(Long courseId,Long classId,Long cpi,Long personId) throws Exception {
        Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/work-stastics/stu-works?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=s&pEnc=&page=1&pageSize=16&personId="+personId)
                .get()
                .build();
        ClassScoreSummary classScoreSummary=new ClassScoreSummary();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            log.info("response:{}",string);
            JSONObject jsonObject = JSON.parseObject(string);
            Map<String, Double>  map=new HashMap<>();
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            Integer keyFocus=0;
            Integer secondary=0;
            Integer soSo=0;
            Integer excellent=0;
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                Double avgWorkScore1 = tmp.getDouble("stuOriginScore");
                if (avgWorkScore1==null){
                    keyFocus=keyFocus+1;
                }else if (avgWorkScore1<60){
                    keyFocus=keyFocus+1;
                }else if ( avgWorkScore1<=69 ) {
                    secondary=secondary+1;
                }else if ( avgWorkScore1<=84 ) {
                    soSo=soSo+1;
                }else {
                    excellent=excellent+1;
                }
            }
            classScoreSummary.setKeyFocus(keyFocus);
            classScoreSummary.setSecondary(secondary);
            classScoreSummary.setSoSo(soSo);
            classScoreSummary.setExcellent(excellent);

        }catch (Exception e){
            log.info("错误为{}",e);
            //            throw new Exception("获取分数失败");
            classScoreSummary.setKeyFocus(0);
            classScoreSummary.setSecondary(0);
            classScoreSummary.setSoSo(0);
            classScoreSummary.setExcellent(0);
            return classScoreSummary;
        }
        return classScoreSummary;
    }

}
